//
//  DR_SelectOpVC.swift
//  DocReaderRP
//
//  Created by  mac on 2025/11/19.
//

import UIKit
import SnapKit
import Toast_Swift

class DR_SelectOpVC: DR_BaseVC {
    
    private var allFiles: [DR_FileModel] = []
    private var selectedFileIndices: Set<Int> = []
    
    private let collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .vertical
        layout.minimumLineSpacing = 16
        layout.minimumInteritemSpacing = 12
        layout.sectionInset = UIEdgeInsets(top: 0, left: 15, bottom: 15, right: 15)
        
        let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
        cv.backgroundColor = .white
        cv.showsVerticalScrollIndicator = false
        cv.register(DR_SelectOpFileCell.self, forCellWithReuseIdentifier: DR_SelectOpFileCell.identifier)
        return cv
    }()
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        // 清除所有选择状态
        selectedFileIndices.removeAll()
        selectAllButton.isSelected = false
        
        loadFiles()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
        setupConstraints()
        
        closeButton.addTarget(self, action: #selector(clickCloseButton), for: .touchUpInside)
        selectAllButton.addTarget(self, action: #selector(clickSelectAllButton), for: .touchUpInside)
        shareButton.addTarget(self, action: #selector(clickShareButton), for: .touchUpInside)
        deleteButton.addTarget(self, action: #selector(clickDeleteButton), for: .touchUpInside)
        
        updateTitle()
    }
    
    private func setupUI() {
        view.addSubview(closeButton)
        view.addSubview(titleLabel)
        view.addSubview(selectAllButton)
        view.addSubview(collectionView)
        view.addSubview(bottomContainerView)
        
        bottomContainerView.addSubview(shareButton)
        bottomContainerView.addSubview(deleteButton)
        
        // Share 按钮内容
        shareButton.addSubview(shareIconView)
        shareButton.addSubview(shareLabel)
        
        // Delete 按钮内容
        deleteButton.addSubview(deleteIconView)
        deleteButton.addSubview(deleteLabel)
        
        collectionView.delegate = self
        collectionView.dataSource = self
    }
    
    private func setupConstraints() {
        
        let halfW = w_screen/2
        
        closeButton.snp.makeConstraints { make in
            make.leading.equalToSuperview().offset(12)
            make.top.equalTo(view.safeAreaLayoutGuide)
            make.width.height.equalTo(44)
        }
        
        titleLabel.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.centerY.equalTo(closeButton)
        }
        
        selectAllButton.snp.makeConstraints { make in
            make.trailing.equalToSuperview().offset(-12)
            make.centerY.equalTo(closeButton)
        }
        
        collectionView.snp.makeConstraints { make in
            make.leading.trailing.equalToSuperview()
            make.top.equalTo(closeButton.snp.bottom).offset(16)
            make.bottom.equalTo(bottomContainerView.snp.top)
        }
        
        bottomContainerView.snp.makeConstraints { make in
            make.leading.trailing.bottom.equalToSuperview()
            make.height.equalTo(100)
        }
        
        shareButton.snp.makeConstraints { make in
            make.trailing.equalToSuperview().offset(-halfW - 20)
            make.top.equalToSuperview().offset(6)
            make.width.equalTo(80)
            make.height.equalTo(60)
        }
        
        shareIconView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalToSuperview().offset(8)
            make.width.height.equalTo(24)
        }
        
        shareLabel.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(shareIconView.snp.bottom).offset(8)
            make.leading.trailing.equalToSuperview()
        }
        
        deleteButton.snp.makeConstraints { make in
            make.leading.equalToSuperview().offset(halfW + 20)
            make.centerY.width.height.equalTo(shareButton)
        }
        
        deleteIconView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalToSuperview().offset(8)
            make.width.height.equalTo(24)
        }
        
        deleteLabel.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(deleteIconView.snp.bottom).offset(8)
            make.leading.trailing.equalToSuperview()
        }
    }
    
    // MARK: - 加载文件列表
    private func loadFiles() {
        allFiles = DR_FileManager.shared.getAllFiles()
        collectionView.reloadData()
        updateTitle()
    }
    
    // MARK: - 更新标题
    private func updateTitle() {
        let count = selectedFileIndices.count
        if count == 0 {
            titleLabel.text = "sel_title".localized
        } else {
            titleLabel.text = "\(count) " + "sel_titleNum".localized
        }
    }
    
    // MARK: - Actions
    @objc private func clickCloseButton() {
        self.navigationController?.popViewController(animated: true)
    }
    
    @objc private func clickSelectAllButton() {
        if selectedFileIndices.count == allFiles.count {
            // 全部已选中，取消全选
            selectedFileIndices.removeAll()
            selectAllButton.isSelected = false
        } else {
            // 全选
            selectedFileIndices = Set(0..<allFiles.count)
            selectAllButton.isSelected = true
        }
        collectionView.reloadData()
        updateTitle()
    }
    
    @objc private func clickShareButton() {
        guard !selectedFileIndices.isEmpty else {
            view.makeToast("sel_selectOne".localized, duration: 2.0, position: .center)
            return
        }
        
        let selectedFiles = selectedFileIndices.sorted().compactMap { index -> DR_FileModel? in
            guard index >= 0 && index < allFiles.count else { return nil }
            return allFiles[index]
        }
        
        guard !selectedFiles.isEmpty else {
            view.makeToast("sel_selectOne".localized, duration: 2.0, position: .center)
            return
        }
        
        // 分享选中的文件
        let fileURLs = selectedFiles.map { $0.fileURL }
        let activityVC = UIActivityViewController(activityItems: fileURLs, applicationActivities: nil)
        
        // 适配iPad
        if let popover = activityVC.popoverPresentationController {
            popover.sourceView = view
            popover.sourceRect = CGRect(x: view.bounds.midX, y: view.bounds.midY, width: 0, height: 0)
            popover.permittedArrowDirections = []
        }
        
        present(activityVC, animated: true)
    }
    
    @objc private func clickDeleteButton() {
        guard !selectedFileIndices.isEmpty else {
            view.makeToast("sel_selectOne".localized, duration: 2.0, position: .center)
            return
        }
        
        let selectedFiles = selectedFileIndices.sorted().compactMap { index -> DR_FileModel? in
            guard index >= 0 && index < allFiles.count else { return nil }
            return allFiles[index]
        }
        
        guard !selectedFiles.isEmpty else {
            view.makeToast("sel_selectOne".localized, duration: 2.0, position: .center)
            return
        }
        
        // 显示删除确认弹窗
        let deleteSheet = DR_DeleteConfirmSheet()
        
        deleteSheet.onDelete = { [weak self] in
            guard let self = self else { return }
            var successCount = 0
            var failCount = 0
            
            for fileModel in selectedFiles {
                do {
                    // 从收藏中移除
                    DR_FileManager.shared.removeFavorite(fileModel)
                    try FileManager.default.removeItem(at: fileModel.fileURL)
                    successCount += 1
                } catch {
                    failCount += 1
                }
            }
            
            // 发送文件导入通知，刷新文件列表
            NotificationCenter.default.post(name: NSNotification.Name("FileImported"), object: nil)
            
            // 刷新当前页面
            self.selectedFileIndices.removeAll()
            self.selectAllButton.isSelected = false
            self.loadFiles()
            
            if failCount > 0 {
                self.view.makeToast("删除完成，成功: \(successCount)，失败: \(failCount)", duration: 2.0, position: .center)
            } else {
                self.view.makeToast("common_delSuccess".localized, duration: 2.0, position: .center)
            }
        }
        
        deleteSheet.onCancel = {
            // 取消操作，不需要处理
        }
        
        // 确保显示在 window 或 tabBarController 的 view 上
        if let window = UIApplication.shared.keyWindowCompat {
            deleteSheet.show(in: window)
        } else if let tabBarController = self.tabBarController {
            deleteSheet.show(in: tabBarController.view)
        } else {
            deleteSheet.show(in: view)
        }
    }
    
    // MARK: - UI Components
    private let closeButton: UIButton = {
        let v = UIButton(type: .custom)
        v.setImage("choose_close".toImage, for: .normal)
        return v
    }()
    
    private let titleLabel: UILabel = {
        let v = UILabel()
        v.text = "sel_title".localized
        v.textAlignment = .center
        v.font = UIFont.systemFont(ofSize: 16, weight: .medium)
        v.textColor = .black
        return v
    }()
    
    private let selectAllButton: UIButton = {
        let v = UIButton(type: .custom)
        v.setTitle("sel_all".localized, for: .normal)
        v.setTitleColor(.black, for: .normal)
        v.titleLabel?.font = UIFont.systemFont(ofSize: 16)
        return v
    }()
    
    private let bottomContainerView: UIView = {
        let v = UIView()
        v.backgroundColor = .white
        return v
    }()
    
    private let shareButton: UIButton = {
        let button = UIButton(type: .custom)
        return button
    }()
    
    private let shareIconView: UIImageView = {
        let v = UIImageView()
        v.image = "more_share".toImage
        v.contentMode = .scaleAspectFill
        return v
    }()
    
    private let shareLabel: UILabel = {
        let v = UILabel()
        v.text = "more_share".localized
        v.textColor = .black
        v.font = UIFont.systemFont(ofSize: 14)
        v.textAlignment = .center
        return v
    }()
    
    private let deleteButton: UIButton = {
        let button = UIButton(type: .custom)
        return button
    }()
    
    private let deleteIconView: UIImageView = {
        let v = UIImageView()
        v.image = "more_del".toImage
        v.contentMode = .scaleAspectFill
        return v
    }()
    
    private let deleteLabel: UILabel = {
        let v = UILabel()
        v.text = "common_del".localized
        v.textColor = .black
        v.font = UIFont.systemFont(ofSize: 14)
        v.textAlignment = .center
        return v
    }()
}

// MARK: - UICollectionViewDataSource, UICollectionViewDelegate
extension DR_SelectOpVC: UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return allFiles.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: DR_SelectOpFileCell.identifier, for: indexPath) as! DR_SelectOpFileCell
        let fileModel = allFiles[indexPath.item]
        let isSelected = selectedFileIndices.contains(indexPath.item)
        
        cell.configure(with: fileModel, isSelected: isSelected)
        
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let index = indexPath.item
        
        if selectedFileIndices.contains(index) {
            // 如果已选中，取消选择
            selectedFileIndices.remove(index)
        } else {
            // 如果未选中，选择
            selectedFileIndices.insert(index)
        }
        
        // 更新全选按钮状态
        if selectedFileIndices.count == allFiles.count {
            selectAllButton.isSelected = true
        } else {
            selectAllButton.isSelected = false
        }
        
        // 刷新当前 cell
        if let cell = collectionView.cellForItem(at: indexPath) as? DR_SelectOpFileCell {
            cell.configure(with: allFiles[index], isSelected: selectedFileIndices.contains(index))
        }
        
        updateTitle()
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let w = (w_screen - 30 - 24) / 3
        return CGSize(width: w, height: 170)
    }
}

// MARK: - DR_SelectOpFileCell
class DR_SelectOpFileCell: UICollectionViewCell {
    
    static let identifier = "DR_SelectOpFileCell"
    
    private let containerView: UIImageView = {
        let view = UIImageView()
        view.backgroundColor = "#F6F7FF".toColor
        view.contentMode = .scaleAspectFill
        view.layer.cornerRadius = 20
        view.layer.masksToBounds = true
        return view
    }()
    
    private let fileNameLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFont(ofSize: 14, weight: .medium)
        label.textColor = .black
        label.textAlignment = .center
        label.lineBreakMode = .byTruncatingMiddle
        return label
    }()
    
    private let checkmarkBtn: UIButton = {
        let v = UIButton(type: .custom)
        v.setImage("choose_check".toImage, for: .normal)
        v.setImage("choose_checked".toImage, for: .selected)
        return v
    }()
    
    private let fileImage: UIImageView = {
        let v = UIImageView()
        v.image = "home_file".toImage
        v.contentMode = .scaleAspectFill
        return v
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
        setupConstraints()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        contentView.addSubview(containerView)
        containerView.addSubview(fileImage)
        contentView.addSubview(fileNameLabel)
        contentView.addSubview(checkmarkBtn)
    }
    
    private func setupConstraints() {
        containerView.snp.makeConstraints { make in
            make.leading.trailing.top.equalToSuperview()
            make.height.equalTo(148)
        }
        
        fileImage.snp.makeConstraints { make in
            make.centerX.centerY.equalToSuperview()
            make.width.height.equalTo(60)
        }
        
        fileNameLabel.snp.makeConstraints { make in
            make.top.equalTo(containerView.snp.bottom).offset(6)
            make.leading.trailing.equalToSuperview()
            make.height.equalTo(16)
        }
        
        checkmarkBtn.snp.makeConstraints { make in
            make.trailing.top.equalToSuperview().inset(10)
            make.width.height.equalTo(20)
        }
    }
    
    func configure(with fileModel: DR_FileModel, isSelected: Bool) {
        fileNameLabel.text = fileModel.displayName
        checkmarkBtn.isSelected = isSelected
        
        // 根据文件类型加载预览图
        if fileModel.fileType == .pdf {
            // PDF文件加载缩略图
            DispatchQueue.global(qos: .userInitiated).async { [weak self] in
                let thumbnail = DR_PDFTool.shared.getPDFThumbnail(fileURL: fileModel.fileURL, size: CGSize(width: 110, height: 150))
                
                DispatchQueue.main.async {
                    if let thumbnail = thumbnail {
                        self?.containerView.image = thumbnail
                        self?.fileImage.isHidden = true
                    } else {
                        self?.containerView.image = nil
                        self?.fileImage.isHidden = false
                        self?.fileImage.image = UIImage(named: fileModel.fileType.iconName)
                    }
                }
            }
        } else {
            // 其他文件类型显示默认图标
            containerView.image = nil
            fileImage.isHidden = false
            fileImage.image = UIImage(named: fileModel.fileType.iconName)
        }
    }
}
